<template>
  <div class="app-container">
    <el-form ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类">
        <el-cascader
            :props="categoryProps"
            style="width: 100%"
            v-model="queryCategoryList"
            @change="handleCategoryChange"
        />
      </el-form-item>

      <el-form-item label="品牌">
        <el-select
            class="m-2"
            placeholder="选择品牌"
            size="small"
            style="width: 100%"
            v-model="queryParams.brandId"
        >
          <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" id="reset-all" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            @click="handleEdit"
            :disabled="single"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleRemove"
            :disabled="multiple"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据展示表格 -->
    <el-table :data="categoryBrandList" v-loading="loading" @selection-change="selectChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="分类名称" prop="categoryName"/>
      <el-table-column label="品牌名称" prop="brandName"/>
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类品牌对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryBrandRef" :model="form" label-width="80px">
        <el-form-item label="分类" prop="categoryIdList">
          <el-cascader
              :props="categoryProps"
              v-model="form.categoryIdList"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
              v-model="form.brandId"
              class="m-2"
              placeholder="选择品牌"
              size="small"
          >
            <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="summit">确 定</el-button>
          <el-button @click="resetForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页条组件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

  </div>
</template>

<script setup name="CategoryBrand">
// ================数据模型定义  start ==================================

//==================1.导入区域=====================
//导入API
import * as catagoryBrand from '@/api/product/categoryBrand'
import {ElMessage, ElMessageBox} from "element-plus";
import {getAllBrandList} from '@/api/product/brand'
import {getTreeList} from '@/api/product/category'

//==================2.变量区域=====================
//proxy 是 Vue3 中的一个新特性，它允许我们在 setup 函数内部直接访问组件实例的属性和方法
const {proxy} = getCurrentInstance();

// 定义搜索表单数据模型
const brandList = ref([])

//查询三级分类数据-搜索 三级分类级联
const props = {
  lazy: true, //懒加载
  value: 'id',
  label: 'name',
  leaf: 'leaf', //叶子节点，获取leaf属性，用于判断是否是叶子节点，叶子节点没孩子，那么不显示>剪头
  async lazyLoad(node, resolve) {   // 加载数据的方法
    if (typeof node.value == 'undefined') {
      node.value = 0
    }
    const {data} = await getTreeList(node.value)
    data.forEach(item => {
      //挂载临时属性，用于判断是否为叶子节点
      item.leaf = !item.hasChildren
    })
    resolve(data)  // 返回数据
  }
};

const categoryProps = ref(props)

// 定义表格数据模型
const categoryBrandList = ref([])

// 分页条数据模型
const total = ref(0)

//加载数据显示的动态加载效果
const loading = ref(false)

//单选框
const single = ref(true)
//复选框
const multiple = ref(true)

const data = reactive({
  queryParams: {
    brandId: null,
    categoryId: null,
    pageNum: 1,
    pageSize: 10
  },
  form: {
    categoryIdList: [],//添加修改选中三个级别的分类id挂到数组上（临时变量作用）。回显数据时，后端返回id数组挂到当前变量上
    categoryId: null,
    brandId: null
  },
  rules: {
    categoryIdList: [
      {required: true, message: "分类不能为空", trigger: "blur"}
    ],
    brandId: [
      {required: true, message: "品牌不能为空", trigger: "blur"}
    ]
  }
})

//导出
const {queryParams, form, rules} = toRefs(data)

//查询品牌的数组
const queryCategoryList = ref([])

//查询条
const showSearch = ref(true)

//弹框头
const title = ref('')

//添加或修改对话框是否显示
const open = ref(false)

//复选数组
const ids = ref([])

//==================3.事件处理区域==================

//分页
function getList() {
  loading.value = true
  catagoryBrand.getList(queryParams.value).then(result => {
    categoryBrandList.value = result.rows
    total.value = result.total
    loading.value = false
  })
}

//搜索方法
function handleQuery() {
  getList()
}

//重置方法
function resetQuery() {
  queryParams.value = {
    brandId: null,
    categoryId: null,
    pageNum: 1,
    pageSize: 10
  }
  queryCategoryList.value = null
  getList()
}

//查询所有品牌
function getBrand() {
  getAllBrandList().then((result) => {
    brandList.value = result.rows
  })
}

//选中搜索 分类下拉列选数据 会触发change事件，需要将三个级别分类数组的索引为2的三分分类id获取，赋值给queryParams.value.categoryId
function handleCategoryChange() {
  queryParams.value.categoryId = queryCategoryList.value[2]
}

//添加弹出框
function handleAdd() {
  open.value = true
  title.value = '添加分类品牌'
}

//提交按钮
function summit() {
  if (form.value.categoryIdList.length == 3) {
    form.value.categoryId = form.value.categoryIdList[2]
  }

  if (form.value.id != null) { //判断id是否为空来决定是增加还是修改
    catagoryBrand.editCategoryBrand(form.value).then((result) => {
      open.value = false
      proxy.$modal.msgSuccess(result.msg)
      getList()
    })
  } else {
    catagoryBrand.addCategoryBrand(form.value).then((result) => {
      open.value = false
      proxy.$modal.msgSuccess(result.msg)
      getList()
    })
  }
}

//取消按钮
function resetForm() {
  open.value = false
  form.value = {
    categoryIdList: null,
  }
  proxy.resetForm('categoryBrandRef')
}

//修改按钮
function handleEdit(row) {
  open.value = true
  title.value = '修改分类品牌'
  let _id = row.id || ids.value
  catagoryBrand.getById(_id).then((result) => {
    form.value = result.data
  })
}

//控制按钮可用不可用
function selectChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = selection.length == 0
}

//删除函数
function handleRemove(row) {
  let _id = row.id || ids.value
  proxy.$modal.confirm("您确定删除数据吗？").then(() => {
    return catagoryBrand.removeCategoryBrand(_id)
  }).then((result) => {
    proxy.$modal.msgSuccess(result.msg)
    getList()
  }).catch((e) => {
    if ('cancel' == e) {
      proxy.$modal.msgSuccess("取消删除")
    } else {
      proxy.$modal.msgError("删除失败" + e)
    }
  })
}


//调用查询所有品牌函数
getBrand()

//调用分页函数
getList()

// =========================数据模型定义 end==============================
</script>